/**
 * @Controller 文件上传 
 * */
const Controller = require('egg').Controller;

// 定义创建接口的请求参数规则
const deleteRule = {
  id: 'string',
};
class FileUploadController extends Controller {

  /**
   * @Router GET /api/v1/files
   * @Request query number page 当前页（1）
   * @Request query number pageSize 分页大小（20）
   * @Request header string authorization
   * @Response 200 createFilesResponse 响应
   * @Summary 获取文件列表
   */
  async index() {
    const { ctx } = this;
    try {
      const data = await ctx.service.file.findFiles(ctx.query);
      ctx.body = {
        code: 200,
        data,
        success: true,
        msg: '',
      }
    } catch (error) {
      throw error;
    }
  }

  async creat() {

  }

  /**
     * @Router POST /api/v1/upload
     * @Request formData files url 文件上传
     * @Response 200 baseResponse 响应
     * @Summary 用户上传图片，并返回上传链接
     */
  async upload() {
    const { ctx } = this;
    let result;
    const stream = await ctx.getFileStream();
    const ocr = stream.fields && stream.fields.scene === '0020001';
    const name = stream.filename;
    let hashName = new Date().getTime();
    try {
      result = await ctx.app.fullQiniu.uploadStream('block_editor/upload/images/' + hashName, stream);
      if (result.ok) {
        const fileData = {
          fileName: name,
          type: stream.mimeType,
          url: result.url
        }
        if(ctx.state.user && ctx.state.user.id != '1f6ad2a0-d3d5-11e9-8fe8-db182b57b855') {
          fileData.creator = ctx.state.user.id
        }
        const file = await ctx.service.file.creatFile(fileData);
        if (file) {
          let data;
          if (ocr) {
            data = await ctx.service.baidu.baiduOcr({ url: result.url });
          }
          let resultData = { imgUrl: result.url };
          if (ocr && data) {
            resultData.ocr = JSON.parse(data.toString())
          }
          ctx.body = {
            code: 200,
            data: resultData,
            success: true,
            msg: `上传成功`
          };
        }
      }
    } catch (err) {
      console.log(err);
      throw err;
    };
  }

  /**
    * @Router POST /api/v1/deleteFile
    * @Request params number id 文件上传
    * @Response 200 baseResponse 响应
    * @Summary 用户删除图片，并返回删除结果
    */
  async deleteFile() {
    const { ctx } = this;
    const result = await ctx.service.file.deleteFile(ctx.params.id);
    if (result.ok) {
      ctx.body = {
        code: 200,
        data: {},
        success: true,
        msg: '删除成功'
      }
    }
  }


  async downloadQRImage() {
    const { ctx } = this;
    ctx.validate(ctx.rule.downloadQRImageRequest, ctx.request.body);
    try {
      const token = await ctx.service.wx.getAccessToken()
      const template = await ctx.service.template.findOneTemplate(ctx.request.body.id);
      const result = await ctx.service.file.downloadQrCodeImage({ ...ctx.request.body, ...template }, token)
      ctx.body = {
        code: 200,
        data: result,
        success: true,
        msg: '成功'
      }
    } catch (err) {
      throw err
    }
  }

  async uploadImageByUrl() {
    const { ctx } = this;
    const { url } = ctx.request.body
    const fileData = {
      fileName: url,
      url: url
    }
    if(ctx.state.user && ctx.state.user.id != '1f6ad2a0-d3d5-11e9-8fe8-db182b57b855') {
      fileData.creator = ctx.state.user.id
    }
    const file = await ctx.service.file.creatFile(fileData);
    if (file) {
      ctx.body = {
        code: 200,
        data: { imgUrl: url },
        success: true,
        msg: `上传成功`
      };
    }
  }
}

module.exports = FileUploadController;
